import sys

from paramiko.client import SSHClient

from jobs_agency.platforms.ssh import ssh_execute
from .config import TencentCloudClientConfig


def make_prepare_func(tcc_config: TencentCloudClientConfig):
    def new_prepare_func(ssh_client: SSHClient):
        print("Configuring tccli ...", file=sys.stderr)
        ssh_execute(ssh_client, (
            "set -e\n"
            "python3 -m pip install --upgrade tccli\n"
            f"tccli configure set secretId {tcc_config.secret_id}\n"
            f"tccli configure set secretKey {tcc_config.secret_key}\n"
            f"tccli configure set region {tcc_config.region}"))

    return new_prepare_func


def make_release_script(instance_id: str):
    return f"""
while true; do
  echo 'Suicide (instance_id={instance_id})' >&2
  tccli cvm TerminateInstances --InstanceIds '["{instance_id}"]'

  if [ $? -eq 0 ]; then
    echo "success" >&2
    break
  else
    echo "retry after 30s" >&2
    sleep 30
  fi 
done"""
